﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SMSROUTER.Business;
using PluggableModulesInterface;
using StorageManagement;
using Settings;
using MTRouterSMSBrandName.SMSBrandname;
using System.Configuration;
using PluggableModulesRouter;
using SMSROUTER.StorageManagement;

namespace MTRouterSMSBrandName
{
    public class Router : WorkingBaseMTWebServiceRouter
    {
        #region Properties and Fields
        private SMSBrandname.SMSBrandname _SmsRouterObject = new SMSBrandname.SMSBrandname();
        protected override System.Web.Services.Protocols.SoapHttpClientProtocol SmsRouterObject
        {
            get
            {
                return _SmsRouterObject;
            }
        }

        public string UserName
        {
            get
            {
                return GetConfig("UserName");
            }
            set
            {
                SetConfig("UserName", value);
            }
        }

        public string Password
        {
            get
            {
                return GetConfig("Password");
            }
            set
            {
                SetConfig("Password", value);
            }
        }

        private struct Result
        {
            public const long SUCCESS = 1;
            public const long FAIL = 0;
        }
        #endregion

        protected override void SendSms(List<SmsOutWaiting> smsOut)
        {
            int threadId = ThreadID;
            bool enableGetReport = ENABLE_GETREPORT;
            bool logToText = this.EnableLogToText;
            List<SmsRouterReport> listRouterReport = new List<SmsRouterReport>();

            foreach (var item in smsOut)
            {
                try
                {
                    string result = (SmsRouterObject as SMSBrandname.SMSBrandname).SENDSMS(UserName, Password, item.ShortCode, item.DestAddr, item.Message);
                    int returnID = -1;
                    if (int.TryParse(result, out returnID))
                    {
                        SmsOutReportStorage.EnqueueElementData(Key, new SmsOutReportStruct(item.RouterID, item.SmsOutGUID, item.CooperateGUID, DateTime.Now, DateTime.Now, item.RetryOnFailReqTimes, item.RetryOnTimeOutReqTimes, AppSetting.Status.SENT, threadId));
                        if (enableGetReport)
                        {
                            listRouterReport.Add(new SmsRouterReport(item.RouterID, item.SmsOutGUID, item.CooperateGUID, DateTime.Now, null, AppSetting.Status.SENTGATEWAY, threadId, result, null));
                        }
                    }
                    else
                    {
                        SmsOutReportStorage.EnqueueElementData(Key, new SmsOutReportStruct(item.RouterID, item.SmsOutGUID, item.CooperateGUID, DateTime.Now, DateTime.Now, item.RetryOnFailReqTimes, item.RetryOnTimeOutReqTimes, AppSetting.Status.FAIL, threadId));
                        Log.InsertLog(string.Format("[SmsOutGUID = {0}] erorr: {1}", item.SmsOutGUID, result), "SMSBrandname.SENDSMS", ObjectType, AppSetting.WarningType.mt_error, item.CooperateID);
                    }
                    if (logToText)
                    {
                        Log.LogToText(item.SmsOutGUID, result, AppSetting.RouterType.MTROUTER);
                    }
                }
                catch (Exception ex)
                {
                    HandleException<SmsOutWaiting>(ex, AppSetting.WarningType.mt_error, item);
                }
            }

            //Insert dữ liệu report
            if (listRouterReport.Count > 0)
            {
                SmsRouterReport.BulkInsert(listRouterReport);
            }
        }

        protected override void GetReport()
        {
            long startID = 1;
            List<SmsRouterReport> listRouterReport = new List<SmsRouterReport>();
            do
            {
                listRouterReport = SmsRouterReport.GetByRouterID(this.Key, startID, this.BatchSize);
                if (listRouterReport.Count > 0)
                {
                    startID = listRouterReport[listRouterReport.Count - 1].ReportID + 1;
                    foreach (SmsRouterReport item in listRouterReport)
                    {
                        try
                        {
                            long id = 0;
                            long.TryParse(item.StringParam, out id);
                            if (id > 0)
                            {
                                string result = (SmsRouterObject as SMSBrandname.SMSBrandname).Status(this.UserName, this.Password, id, "");
                                //string[] sArray = result.Split('|');
                                //if (sArray.Length >= 2)
                                //{
                                //    string reportStatus = sArray[0], reportTime = sArray[1];
                                //    if (!string.IsNullOrEmpty(reportStatus))
                                //    {
                                //        switch (reportStatus)
                                //        {
                                //            case "DELIVERED":
                                //                item.Status = AppSetting.Status.SENT;
                                //                try
                                //                {
                                //                    item.ReportTime = DateTime.Parse(reportTime);
                                //                }
                                //                catch (Exception)
                                //                {
                                //                    Log.InsertLog(string.Format("[SmsOutGUID = {0}] reportTime error: {1}", item.SmsOutGUID, reportTime), "SMSBrandname.Status", ObjectType, AppSetting.WarningType.mt_error, null);
                                //                }
                                //                break;
                                //            default:
                                //                item.Status = AppSetting.Status.FAIL;
                                //                try
                                //                {
                                //                    item.ReportTime = DateTime.Parse(reportTime);
                                //                }
                                //                catch (Exception)
                                //                {
                                //                    Log.InsertLog(string.Format("[SmsOutGUID = {0}] reportTime error: {1}", item.SmsOutGUID, reportTime), "SMSBrandname.Status", ObjectType, AppSetting.WarningType.mt_error, null);
                                //                }
                                //                Log.InsertLog(string.Format("[SmsOutGUID = {0}] erorr: {1}", item.SmsOutGUID, result), "SMSBrandname.Status", ObjectType, AppSetting.WarningType.mt_error, null);
                                //                break;
                                //        }
                                //    }
                                //}
                            }
                            else
                            {
                                item.Status = AppSetting.Status.FAIL;
                                item.ReportTime = DateTime.Now;
                                Log.InsertLog(string.Format("[SmsOutGUID = {0}] erorr: {1}", item.SmsOutGUID, "Send ID is not valid"), "SMSBrandname.Status", ObjectType, AppSetting.WarningType.mt_error, null);
                            }
                        }
                        catch (Exception ex)
                        {
                            HandleException<SmsRouterReport>(ex, AppSetting.WarningType.mt_error, item);
                        }
                    }
                    SmsRouterReport.BatchUpdate(listRouterReport);
                }
            }
            while (listRouterReport.Count > 0);
        }
    }
}